<template>
  <div class="discussions-page">
    <el-page-header>
      <template slot="content">
        <h1>讨论区</h1>
        <p>参与包相关讨论，分享经验和解决问题</p>
      </template>
    </el-page-header>
    
    <el-card class="discussions-card">
      <template slot="header">
        <div class="card-header">
          <span>讨论列表</span>
          <el-button type="primary" size="small" @click="showCreateDialog">发起讨论</el-button>
        </div>
      </template>
      
      <div class="search-filter-container" style="margin-bottom: 16px;">
        <el-input 
          v-model="searchQuery"
          placeholder="搜索讨论标题或内容"
          prefix-icon="el-icon-search"
          style="width: 300px; margin-right: 16px;"
          @keyup.enter.native="searchDiscussions"
        />
        
        <el-select 
          v-model="selectedPackageId"
          placeholder="选择关联包"
          style="width: 180px; margin-right: 16px;"
          @change="searchDiscussions"
        >
          <el-option label="全部" value="" />
          <el-option 
            v-for="pkg in packages"
            :key="pkg.id"
            :label="pkg.name"
            :value="pkg.id"
          />
        </el-select>
        
        <el-select 
          v-model="sortBy"
          placeholder="排序方式"
          style="width: 120px; margin-right: 16px;"
          @change="searchDiscussions"
        >
          <el-option label="最新发布" value="newest" />
          <el-option label="最多评论" value="mostComments" />
        </el-select>
        
        <el-button type="primary" @click="searchDiscussions">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      
      <div v-if="loading" class="loading-container">
        <el-loading-spinner />
      </div>
      
      <div v-else-if="discussions.length === 0" class="empty-state">
        <p>暂无讨论内容</p>
      </div>
      
      <el-table 
        v-else
        :data="discussions"
        style="width: 100%"
      >
        <el-table-column prop="title" label="标题" width="400">
          <template slot-scope="scope">
            <a href="javascript:void(0)" @click="viewDiscussion(scope.row.id)" class="discussion-title">
              {{ scope.row.title }}
            </a>
            <el-tag 
              v-if="scope.row.package"
              size="small" 
              style="margin-left: 8px; cursor: pointer;"
              @click.stop="viewPackage(scope.row.package.id)"
            >
              {{ scope.row.package.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="内容预览" width="300">
          <template slot-scope="scope">
            {{ truncateText(scope.row.content, 100) }}
          </template>
        </el-table-column>
        <el-table-column prop="author" label="作者" width="100" />
        <el-table-column prop="comments" label="评论数" width="80" align="center">
          <template slot-scope="scope">
            <el-badge :value="scope.row.comments || 0" class="item" />
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="发布时间" width="160" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button 
              type="text" 
              size="small" 
              @click="viewDiscussion(scope.row.id)"
            >
              查看
            </el-button>
            <el-button 
              v-if="isAuthor(scope.row.author)"
              type="text" 
              size="small" 
              danger 
              @click="deleteDiscussion(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div v-if="discussions.length > 0" class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </el-card>
    
    <!-- 创建讨论对话框 -->
    <el-dialog 
      title="发起讨论"
      :visible.sync="createDialogVisible"
      width="700px"
    >
      <el-form 
        ref="discussionForm"
        :model="discussionForm"
        :rules="discussionRules"
        label-width="80px"
      >
        <el-form-item label="关联包">
          <el-select 
            v-model="discussionForm.packageId"
            placeholder="选择关联的npm包（可选）"
          >
            <el-option label="无关联包" value="" />
            <el-option 
              v-for="pkg in packages"
              :key="pkg.id"
              :label="pkg.name"
              :value="pkg.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="discussionForm.title" placeholder="请输入讨论标题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input 
            v-model="discussionForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入讨论内容，详细描述您的问题或经验"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createDiscussion">发布讨论</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'DiscussionsPage',
  layout: 'default',
  data() {
    return {
      discussions: [],
      packages: [],
      loading: false,
      searchQuery: '',
      selectedPackageId: '',
      sortBy: 'newest',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      
      // 创建讨论对话框
      createDialogVisible: false,
      discussionForm: {
        packageId: '',
        title: '',
        content: ''
      },
      discussionRules: {
        title: [
          { required: true, message: '请输入讨论标题', trigger: 'blur' },
          { min: 5, max: 100, message: '标题长度在 5 到 100 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入讨论内容', trigger: 'blur' },
          { min: 10, max: 2000, message: '内容长度在 10 到 2000 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  async fetch() {
    await this.loadDiscussions()
    await this.loadPackages()
  },
  methods: {
    async loadDiscussions() {
      this.loading = true
      try {
        const response = await this.$axios.get('/discussions', {
          params: {
            query: this.searchQuery,
            packageId: this.selectedPackageId,
            sortBy: this.sortBy,
            page: this.currentPage,
            pageSize: this.pageSize
          }
        })
        this.discussions = response.items || []
        this.total = response.total || 0
      } catch (error) {
        this.$message.error('加载讨论列表失败：' + error.message)
        this.discussions = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    
    async loadPackages() {
      try {
        const response = await this.$axios.get('/packages', {
          params: { pageSize: 100 } // 获取前100个包作为选项
        })
        this.packages = response.items || []
      } catch (error) {
        this.$message.error('加载包列表失败：' + error.message)
        this.packages = []
      }
    },
    
    searchDiscussions() {
      this.currentPage = 1
      this.loadDiscussions()
    },
    
    resetSearch() {
      this.searchQuery = ''
      this.selectedPackageId = ''
      this.sortBy = 'newest'
      this.searchDiscussions()
    },
    
    handleSizeChange(size) {
      this.pageSize = size
      this.loadDiscussions()
    },
    
    handleCurrentChange(current) {
      this.currentPage = current
      this.loadDiscussions()
    },
    
    formatDate(dateString) {
      if (!dateString) return '未知'
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    
    truncateText(text, maxLength) {
      if (!text || text.length <= maxLength) return text
      return text.substring(0, maxLength) + '...'
    },
    
    isAuthor(author) {
      // 在实际应用中，这里应该检查当前登录用户是否是作者
      // 这里简单假设当前用户是 'admin'
      return author === 'admin'
    },
    
    viewDiscussion(id) {
      this.$router.push(`/discussions/${id}`)
    },
    
    viewPackage(id) {
      this.$router.push(`/packages/${id}`)
    },
    
    showCreateDialog() {
      this.discussionForm = {
        packageId: '',
        title: '',
        content: ''
      }
      
      if (this.$route.query.packageId) {
        this.discussionForm.packageId = this.$route.query.packageId
      }
      
      if (this.$refs.discussionForm) {
        this.$refs.discussionForm.resetFields()
      }
      
      this.createDialogVisible = true
    },
    
    async createDiscussion() {
      this.$refs.discussionForm.validate(async (valid) => {
        if (valid) {
          try {
            await this.$axios.post('/discussions', this.discussionForm)
            this.$message.success('讨论发布成功')
            this.createDialogVisible = false
            await this.loadDiscussions()
          } catch (error) {
            this.$message.error('发布失败：' + error.message)
          }
        }
      })
    },
    
    async deleteDiscussion(id) {
      this.$confirm('确定要删除这个讨论吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await this.$axios.delete(`/discussions/${id}`)
          this.$message.success('删除成功')
          await this.loadDiscussions()
        } catch (error) {
          this.$message.error('删除失败：' + error.message)
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.discussions-page {
  padding: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-filter-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #8c8c8c;
}

.discussion-title {
  color: #262626;
  font-weight: 500;
  text-decoration: none;
  transition: color 0.3s ease;
}

.discussion-title:hover {
  color: #1890ff;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>